const router = require('koa-router')()
const db = require('../utils/mysql')
const { sendEmail } = require('../utils/sendEmail')
const { createCode } = require('../utils')
const dayjs = require('dayjs')
const { loginConf } = require('../config/default')
const jwt = require('jsonwebtoken')

router.prefix('/api')

router.get('/',  async (ctx, next) => {
  ctx.body = await db.query(`select * from player`)
})

// router.get('/bar', function (ctx, next) {
//   ctx.body = 'this is a users/bar response'
// })

// 获取分数
router.get('/score', async (ctx, next) => {
  const res = await db.query(`SELECT score, p.id as id, email
  FROM player as p, score as s
  WHERE p.id=s.user_id
  ORDER BY s.score DESC;`)
  ctx.body = {
    ...res,
    ...ctx.body
  }
})

// 更新分数
router.get('/save_score', async(ctx, next) => {
  const { score: bestScore } = ctx.query
  let token = ctx.cookies.get('token')
  if (!token) {
    return
  }
  const tokenItem = jwt.verify(token, loginConf.tokenSecret)

  const { email } = tokenItem
  const user = await db.query(`SELECT p.id, score
    FROM player as p, score as s
    WHERE p.email='${email}' AND p.id=s.user_id`
  )
  const { score, id } = user.data[0]
  if (+bestScore > score) {
    ctx.body = await db.query(`UPDATE score
      SET score = '${bestScore}'
      WHERE user_id = '${id}';`
    )
  } else {
    ctx.body = {
      code: 0,
      msg: '未打破记录：'+ score
    }
  }
})

// 登录
router.post('/login', async (ctx, next) => {
  const { email, code, score } = ctx.request.body
  const user = await db.query(`SELECT email, extra, id
    FROM player
    WHERE email = '${email}'
  `)
  if (user.code === 0) {
    const { emailCode, dueTime } = JSON.parse(user.data[0].extra)
    // 判断是否超时
    if(dayjs().valueOf() > dayjs(dueTime).valueOf()) {
      return ctx.body = {
        code: 1,
        msg: '验证码超时，请重新获取'
       }
    } else {
      if (emailCode === code) {
        // 登录成功
        let payload = {
          email,
          time: new Date().getTime(),
          timeout: loginConf.timeout * 1000
        }
        let token = jwt.sign(payload, loginConf.tokenSecret, { expiresIn: 60 * 60 });
        // 设置cookie
        ctx.cookies.set('token', token, {
          maxAge: 60 * 1000 * 60,
        })
        if (score) {
          await db.query(`UPDATE score
            SET score = '${score}'
            WHERE user_id = '${user.data[0].id}';`
          )
          return ctx.body = {
            code: 0,
            msg: '更新分数成功'
          }
        }
        return ctx.body = {
          code: 0,
          msg: '登录成功'
        }
      } else {
        return ctx.body = {
          code: 1,
          msg: '验证码错误，请重新输入'
         }
      }
    }
  }
  ctx.body = user
})

let throttleTime = {}
// 发送验证码
router.get('/send_code', async (ctx, next) => {
  const { email } = ctx.query
  if(!/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(email)) {
    return ctx.body = {
      code: 1,
      msg: '请填写正确的邮箱'
    }
  }
  if (!throttleTime[email]) {
    throttleTime[email] = dayjs().add(1, 'm')
  } else if (dayjs().valueOf() < throttleTime[email].valueOf()) {
    return ctx.body = {
      code: 1,
      msg: '请勿频繁发送验证码，1分钟后再试'
    }
  }
  const emailCode = createCode()
  try {
    const one = await db.query(`SELECT id FROM player WHERE email='${email}'`)
    if(one.data) {
      await db.query(`UPDATE player
        SET extra = '${JSON.stringify({
          emailCode,
          dueTime: dayjs().add(5, 'm') // 5分钟
        })}'
        WHERE email = '${email}';`
      )
    } else {
      await db.query(`INSERT INTO
      player(
        email,
        extra
      )
      VALUES(
        '${email}',
        '${JSON.stringify({
            emailCode,
            dueTime: dayjs().add(10, 'm') // 5分钟
          })}'
        );
      `)
  }

    const sendEmailRes = await sendEmail({
      toEmail: email,
      emailCode
    })
    ctx.body = {
      code: sendEmailRes ? 0 : 1,
      msg: sendEmail
    }
  } catch (err) {
    ctx.body = err
  }
})


module.exports = router

// class CommonModel {
//   async getUserByName (username) {
//     return await db.query(`select * from shop.s_users where username='${username}'`)
//   }
//   async getUserById (id) {
//     return await db.query(`select * from shop.s_users where id='${id}'`)
//   }
// }

// module.exports = new CommonModel()